import { App } from 'vue';

interface DragData {
  attributes: any;
  attributesConfig: any;
  id?: string;
  name: string;
  tagName: string;
  x?: number;
  y?: number;
}

interface Distance {
  distanceX: number;
  distanceY: number;
}

let dragData: DragData;
const distance: Distance = {
  distanceX: 0,
  distanceY: 0,
};

export const drag = function (app: App<Element>) {
  app.directive('drag', {
    mounted(el, binding) {
      const { attr, draggable } = binding.value;
      if (!draggable) return;
      el.setAttribute('draggable', true);
      // 计算点击时鼠标位置相对x、y的差值
      el.addEventListener('mousedown', (event: any) => {
        distance.distanceX = event.clientX - attr.styles.x;
        distance.distanceY = event.clientY - attr.styles.y;
      });
      el.addEventListener('drag', (event: any) => {
        dragData = JSON.parse(JSON.stringify(attr));
      });
    },
  });
};

export const drop = function (app: App<Element>) {
  app.directive('drop', {
    mounted(el, binding) {
      const { dropable } = binding.value;
      if (!dropable) return;
      el.addEventListener('drop', (event: any) => {
        event.preventDefault();
        binding.value.ondrop(event, dragData, distance);
      });
      el.addEventListener('dragover', (event: any) => {
        event.preventDefault();
      });
    },
  });
};

export const stretch = function (app: App<Element>) {
  app.directive('stretch', {
    mounted(el, binding) {
      el.addEventListener('mousemove', (event: any) => {
        console.log(event);
      });
    },
  });
};

export default {};
